<?php
/**
 * Created by PhpStorm.
 * User: 江远
 * Date: 2018/11/30
 * Time: 19:03
 */
namespace app\common\model;

use think\Db;
use think\Model;

class AuthUser extends Model
{
    protected $autoWriteTimestamp = true;

    public function login($data, $code)
    {
        if ($code == 'open') {
            if (!$this->check($data['vercode'])) {
                return ['code' => 40006, 'msg' => '验证码错误'];
            }
        }
        $user = Db::name('auth_user')->where([['username|mobile','eq',$data['username']]])->find();
        if ($user) {
            if($user['frozen'] != '0'){
                return ['code'=>40005,'msg'=>'账号已被冻结'];
            }
            if ($user['password'] == md5(md5($data['password']))) {
                
                $avatar = $user['avatar'] == '' ? '/static/tdmin/images/0.jpg' : $user['avatar'];
                session('avatar', $avatar);
                session('nickname', $user['nickname']);
                session('admin_uid', $user['id']);
                if(empty($user['token'])) {
                    $token = md5($user['id'].time());
                } else {
                    $token = $user['token'];
                }

                $updateData = [
                    'token'         => $token,
                    'lastlogintime' => time(),
                    'lastloginip'   => $_SERVER['REMOTE_ADDR'],
                ];

                Db::name('auth_user')->where('id', 'eq', $user['id'])->update($updateData);
                return ['code' => 0, 'msg' => '登录成功!', 'token' => $token]; //信息正确
            } else {
                return ['code' => 40003, 'msg' => '密码错误，重新输入!','p'=>md5(md5($data['password']))]; //密码错误
            }
        } else {
            return ['code' => 40002, 'msg' => '用户不存在!']; //用户不存在
        }
    }

    public function check($code)
    {
        return captcha_check($code);
    }
}
